const express = require('express');
const router = express.Router();
const Shop = require('../models/shop.model');
const Product = require('../models/product.model');
const User = require('../models/user.model');
const mongoose = require('mongoose');

/**
 * 初始化店铺数据的API端点
 * GET /api/setup/shops
 */
router.get('/shops', async (req, res) => {
  try {
    console.log('开始初始化店铺数据...');

    // 创建测试用户
    let testUser = await User.findOne({ email: 'test@shop.com' });
    if (!testUser) {
      testUser = await User.create({
        name: '测试店主',
        email: 'test@shop.com',
        password: 'password123'
      });
      console.log('创建测试用户成功');
    }

    // 创建测试店铺
    const testShops = [
      {
        name: 'Apple官方旗舰店',
        description: 'Apple官方授权旗舰店，正品保证',
        logo: 'https://picsum.photos/200/200?random=101',
        banner: 'https://picsum.photos/800/300?random=201',
        owner: testUser._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码'],
        rating: {
          overall: 4.9,
          service: 4.9,
          logistics: 4.8,
          description: 4.9
        },
        announcement: '新品iPhone 15系列现货发售',
        tags: ['官方正品', '全国联保'],
        certification: {
          isVerified: true,
          verifiedAt: new Date()
        },
        shipping: {
          freeShippingThreshold: 0,
          shippingFee: 0,
          supportedRegions: ['全国'],
          averageDeliveryTime: 1
        },
        afterSales: {
          returnPolicy: '15天无理由退货',
          warrantyPeriod: 365,
          supportRefund: true,
          supportExchange: true
        },
        stats: {
          totalProducts: 0,
          totalSales: 10000,
          totalOrders: 5000,
          monthlyRevenue: 500000,
          followers: 50000
        }
      },
      {
        name: '小米官方旗舰店',
        description: '小米科技官方旗舰店，米粉专属购物天堂',
        logo: 'https://picsum.photos/200/200?random=102',
        banner: 'https://picsum.photos/800/300?random=202',
        owner: testUser._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码'],
        rating: {
          overall: 4.8,
          service: 4.8,
          logistics: 4.7,
          description: 4.8
        },
        announcement: '小米14系列新品上市，性价比之王',
        tags: ['性价比', '科技潮品'],
        certification: {
          isVerified: true,
          verifiedAt: new Date()
        },
        shipping: {
          freeShippingThreshold: 99,
          shippingFee: 10,
          supportedRegions: ['全国'],
          averageDeliveryTime: 2
        },
        afterSales: {
          returnPolicy: '7天无理由退货',
          warrantyPeriod: 365,
          supportRefund: true,
          supportExchange: true
        },
        stats: {
          totalProducts: 0,
          totalSales: 15000,
          totalOrders: 8000,
          monthlyRevenue: 300000,
          followers: 80000
        }
      },
      {
        name: '京东数码专营店',
        description: '专业数码产品销售，品质保证，服务至上',
        logo: 'https://picsum.photos/200/200?random=103',
        banner: 'https://picsum.photos/800/300?random=203',
        owner: testUser._id,
        type: 'authorized',
        status: 'active',
        categories: ['手机数码', '摄影摄像'],
        rating: {
          overall: 4.6,
          service: 4.6,
          logistics: 4.5,
          description: 4.6
        },
        announcement: '数码新品大促销，限时优惠不容错过',
        tags: ['品质保证', '价格优惠'],
        certification: {
          isVerified: true,
          verifiedAt: new Date()
        },
        shipping: {
          freeShippingThreshold: 299,
          shippingFee: 20,
          supportedRegions: ['全国'],
          averageDeliveryTime: 3
        },
        afterSales: {
          returnPolicy: '7天无理由退货',
          warrantyPeriod: 180,
          supportRefund: true,
          supportExchange: true
        },
        stats: {
          totalProducts: 0,
          totalSales: 12000,
          totalOrders: 6000,
          monthlyRevenue: 200000,
          followers: 30000
        }
      }
    ];

    // 清空现有店铺
    await Shop.deleteMany({});
    console.log('清空现有店铺数据');

    // 创建店铺
    const shops = await Shop.insertMany(testShops);
    console.log(`创建了 ${shops.length} 个店铺`);

    // 获取所有商品并关联到店铺
    const products = await Product.find({});
    console.log(`找到 ${products.length} 个商品`);

    let linkedCount = 0;
    if (products.length > 0) {
      for (let i = 0; i < products.length; i++) {
        const product = products[i];
        let assignedShop = null;

        // 智能分配店铺
        if (product.name.toLowerCase().includes('iphone') ||
          product.name.toLowerCase().includes('ipad') ||
          product.name.toLowerCase().includes('apple') ||
          product.brand?.toLowerCase().includes('apple')) {
          assignedShop = shops.find(shop => shop.name.includes('Apple'));
        } else if (product.name.toLowerCase().includes('小米') ||
          product.brand?.toLowerCase().includes('xiaomi') ||
          product.brand?.toLowerCase().includes('小米')) {
          assignedShop = shops.find(shop => shop.name.includes('小米'));
        } else {
          // 默认分配到京东数码专营店
          assignedShop = shops.find(shop => shop.name.includes('京东数码'));
        }

        if (!assignedShop) {
          assignedShop = shops[i % shops.length];
        }

        // 更新商品的店铺关联
        await Product.findByIdAndUpdate(product._id, { shop: assignedShop._id });
        linkedCount++;
        console.log(`${product.name} → ${assignedShop.name}`);
      }

      // 更新店铺商品统计
      for (const shop of shops) {
        const productCount = await Product.countDocuments({ shop: shop._id });
        await Shop.findByIdAndUpdate(shop._id, {
          'stats.totalProducts': productCount
        });
        console.log(`${shop.name}: ${productCount} 个商品`);
      }
    }

    res.json({
      success: true,
      message: '店铺数据初始化完成',
      data: {
        shopsCreated: shops.length,
        productsLinked: linkedCount,
        shops: shops.map(shop => ({
          id: shop._id,
          name: shop.name,
          type: shop.type,
          productCount: 0 // 将在下次查询时更新
        }))
      }
    });

  } catch (error) {
    console.error('初始化店铺数据失败:', error);
    res.status(500).json({
      success: false,
      message: '初始化失败',
      error: error.message
    });
  }
});

/**
 * 为商品添加规格选择数据
 * GET /api/setup/product-specs
 */
router.get('/product-specs', async (req, res) => {
  try {
    console.log('开始为商品添加规格选择数据...');

    // 获取所有商品
    const products = await Product.find();
    let updatedCount = 0;

    for (const product of products) {
      let specs = {};

      // 根据商品类型添加相应的规格选择
      if (product.name.toLowerCase().includes('iphone')) {
        specs = {
          '颜色': ['深空黑色', '银色', '金色', '深紫色'],
          '容量': ['128GB', '256GB', '512GB', '1TB']
        };
      } else if (product.name.toLowerCase().includes('小米') || product.name.toLowerCase().includes('xiaomi')) {
        specs = {
          '颜色': ['雅川青', '昆仑白', '岩石黑'],
          '容量': ['256GB', '512GB', '1TB']
        };
      } else if (product.name.toLowerCase().includes('airpods')) {
        specs = {
          '颜色': ['白色', '黑色']
        };
      } else if (product.name.toLowerCase().includes('电视')) {
        specs = {
          '尺寸': ['55英寸', '65英寸', '75英寸']
        };
      } else if (product.name.toLowerCase().includes('笔记本')) {
        specs = {
          '配置': ['标准版', '高配版'],
          '颜色': ['银色', '深空灰']
        };
      }

      // 更新商品规格
      if (Object.keys(specs).length > 0) {
        await Product.findByIdAndUpdate(product._id, { specs });
        updatedCount++;
        console.log(`${product.name} - 添加规格:`, Object.keys(specs).join(', '));
      }
    }

    res.json({
      success: true,
      message: '商品规格数据添加完成',
      data: {
        totalProducts: products.length,
        updatedProducts: updatedCount
      }
    });

  } catch (error) {
    console.error('添加商品规格失败:', error);
    res.status(500).json({
      success: false,
      message: '添加规格失败',
      error: error.message
    });
  }
});

/**
 * 获取商品ID列表（用于调试）
 * GET /api/setup/product-ids
 */
router.get('/product-ids', async (req, res) => {
  try {
    const products = await Product.find({}, '_id name').limit(10);

    res.json({
      success: true,
      message: '商品ID列表',
      data: {
        products: products.map(p => ({
          id: p._id.toString(),
          name: p.name
        })),
        total: await Product.countDocuments()
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取商品ID失败',
      error: error.message
    });
  }
});

/**
 * 检查店铺数据状态
 * GET /api/setup/status
 */
router.get('/status', async (req, res) => {
  try {
    const shopCount = await Shop.countDocuments();
    const productCount = await Product.countDocuments();
    const linkedProductCount = await Product.countDocuments({ shop: { $exists: true } });
    const specsProductCount = await Product.countDocuments({ specs: { $exists: true } });

    // 获取一些示例商品ID
    const sampleProducts = await Product.find({}, '_id name').limit(3);

    res.json({
      success: true,
      data: {
        shops: shopCount,
        products: productCount,
        linkedProducts: linkedProductCount,
        specsProducts: specsProductCount,
        linkageRate: productCount > 0 ? (linkedProductCount / productCount * 100).toFixed(1) + '%' : '0%',
        specsRate: productCount > 0 ? (specsProductCount / productCount * 100).toFixed(1) + '%' : '0%',
        sampleProductIds: sampleProducts.map(p => ({
          id: p._id.toString(),
          name: p.name
        }))
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取状态失败',
      error: error.message
    });
  }
});

module.exports = router;
